import React, { useState, useEffect } from "react";
import { Badge, TabBar } from "antd-mobile";
import {
  AppOutline,
  MessageOutline,
  MessageFill,
  UnorderedListOutline,
  UserOutline,
} from "antd-mobile-icons";
import { Outlet, useNavigate, useLocation } from "react-router-dom";

import "./demo2.less";
function TabBars() {
  let navigate = useNavigate();
  let location = useLocation();
  //切换tabbar
  let toggleTabbar = (index) => {
    if (activeKey == index) return;
    console.log("activeKey", activeKey);
    setActiveKey(index);
    navigate(index);
  };
  useEffect(() => {
    //查找当前激活的路径
    for (let i = 0; i < tabbarData.length; i++) {
      if (tabbarData[i].key === location.pathname) {
        setActiveKey(tabbarData[i].key);
        console.log(111111111);

        break;
      } else {
        navigate("/home");
      }
    }
  }, []);
  const tabbarData = [
    {
      key: "/home",
      title: "首页",
      icon: <AppOutline />,
      badge: "5",
    },
    {
      key: "/classfiy",
      title: "分类",
      icon: <UnorderedListOutline />,
      badge: "5",
    },
    {
      key: "/booklist",
      title: "书架",
      icon: (active: boolean) =>
        active ? <MessageFill /> : <MessageOutline />,
      badge: "99+",
    },
    {
      key: "/my",
      title: "我的",
      icon: <UserOutline />,
    },
  ];

  const [activeKey, setActiveKey] = useState("/home");
  return (
    <TabBar
      activeKey={activeKey}
      safeArea={true}
      onChange={(key) => {
        toggleTabbar(key);
      }}
    >
      {tabbarData.map((item) => (
        <TabBar.Item
          key={item.key}
          badge={item.badge}
          icon={item.icon}
          title={item.title}
        />
      ))}
    </TabBar>
  );
}
export default () => {
  return (
    <div className="Mains">
      <div className="Mains_body">
        <Outlet></Outlet>
      </div>
      <div className="bottom">
        <TabBars></TabBars>
      </div>
    </div>
  );
};
